package logic

import (
	"context"
	"duoduo/model/cache"
	"duoduo/model/mysql"
	"duoduo/pkg"
	"fmt"

	"duoduo/duoduorpc/duoduorpc"
	"duoduo/duoduorpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetLogic {
	return &ForgetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetLogic) Forget(in *duoduorpc.ForgetRequest) (*duoduorpc.ForgetResponse, error) {
	// todo: add your logic here and delete this line

	var m mysql.User
	mysql.Db.Debug().Where("account=?", in.Account).Find(&m)
	if m.ID == 0 {
		return nil, fmt.Errorf("账号不存在,请重新输入")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sengSms"+in.Account).Result()
	if in.SengSms != result {
		return nil, fmt.Errorf("短信验证码输入错误,请重新输入")
	}
	s, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.Captcha != s {
		return nil, fmt.Errorf("图形验证码输入错误,请重新输入")
	}
	if m.Password == in.Password {
		return nil, fmt.Errorf("新密码和久密码不能一致")
	}
	if pkg.Md5(in.Password) != pkg.Md5(in.NewPassword) {
		return nil, fmt.Errorf("两次密码不一致")
	}
	m.Password = in.NewPassword
	mysql.Db.Debug().Updates(&m)
	return &duoduorpc.ForgetResponse{
		UserId: int64(m.ID),
	}, nil
}
